package com.zy.config;

import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class FreemarkerHelper {
    public String query(String queryString, String param) {
        if (StringUtils.isEmpty(param)) {
            return queryString;
        }
        String sub ="";
        if (queryString.indexOf("msg") != -1) {
            if(queryString.indexOf("&")!=-1){
                sub = queryString.substring(queryString.indexOf("msg"),queryString.indexOf("&"));
            }else{
                sub = queryString.substring(queryString.indexOf("msg"));
            }

            queryString=  queryString.replace(sub,"");
        }
        String key = param.split("=")[0];
        if (StringUtils.isEmpty(queryString)) {
            return param;
        } else {
            String[] split = queryString.split("&");
            int i = 0;
            for (; i < split.length; i++) {
                if (split[i].indexOf("msg") != -1) {
                    continue;
                }
                if (split[i].contains(key)) {
                    break;
                }
            }
            if (i < split.length) {
                split[i] = param;
                return StringUtils.arrayToDelimitedString(split, "&");
            } else {
                return queryString + "&" + param;
            }

        }
    }

    public Map<String, String> split(String queryString) {
        Map<String, String> result = new HashMap<>();
        if (StringUtils.isEmpty(queryString)) {
            return result;
        }
        String[] split = queryString.split("&");
        for (String s : split) {
            String[] split1 = s.split("=");
            if (split1.length == 2) {
                result.put(split1[0], split1[1]);
            }

        }
        return result;
    }
}
